<!--
 * @FileDescription: 
 * @Author: wangzhichiao<https://github.com/wzc570738205>
 * @Date: 2021-09-17 09:40:08
 * @LastEditors: wangzhichiao<https://github.com/wzc570738205>
 * @LastEditTime: 2021-09-17 10:22:44
-->
<template>
  <div>
    <h1>自定义input:file样式</h1>
    <div class="input-file-container">
      <input class="input-file" id="file" type="file" @change="onFileChange" />
      <label tabindex="0" for="file" class="input-file-trigger">选择文件</label>
    </div>
    <div class="input-file-container">
      <input class="input-file" id="file1" type="file"  @change="onFileChange" />
      <label tabindex="0" for="file1" >
          <el-button @click="handleClick" type="primary">选择文件</el-button>
      </label>
    </div>
    <div v-if="image">
      <el-image style="width: 100px; height: 100px"  :src="image" :preview-src-list="[image]"> </el-image>
      <el-button @click="removeImage" type="primary">清除图片</el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: "",
  components: {},
  data() {
    return {
      image: "",
    };
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    onFileChange(e) {
      var files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      this.createImage(files[0]);
    },
    createImage(file) {
      var reader = new FileReader();
      var vm = this;

      reader.onload = (e) => {
        vm.image = e.target.result;
      };
      reader.readAsDataURL(file);
    },
    removeImage: function(e) {
      this.image = "";
    },
    handleClick(e) {
      this.type = e
      const fileElem = document.getElementById('file1')
      if (fileElem) {
        fileElem.click()
      }
    },
  },
};
</script>
<style >
.input-file-container {
  display: inline-block;
}
.input-file-trigger {
  padding: 14px 45px;
  background: #39d2b4;
  color: #fff;
  font-size: 1em;
  transition: all 0.4s;
  cursor: pointer;
  display: block;
}
.input-file {
  width: 225px;
  opacity: 0;
  padding: 14px 0;
  cursor: pointer;
  display: none;
}
.input-file:hover + .input-file-trigger,
.input-file:focus + .input-file-trigger,
.input-file-trigger:hover,
.input-file-trigger:focus {
  background: #34495e;
  color: #39d2b4;
}
</style>
